package eerbaar.shared.internal.tree.commands;

import java.util.ArrayList;
import java.util.List;

import eerbaar.shared.internal.tree.AbstractNode;
import eerbaar.shared.tree.DefaultPayload;
import eerbaar.shared.tree.INode;
import eerbaar.shared.tree.IPayload;
import eerbaar.shared.tree.NodeFactory;

public class MergeChildrenCmd {

    public MergeChildrenCmd() {
        //
    }

    public void execute(INode node) {

        List<INode> addList = new ArrayList<INode>();
        List<INode> removeList = new ArrayList<INode>();

        INode lastNode = null;
        INode[] children = node.getChildren();
        for (INode n : children) {

            if (lastNode == null) {
                lastNode = n;
                continue;
            }

            IPayload lastPayload = lastNode.getPayload();
            IPayload payload = n.getPayload();
            boolean b1 = (lastPayload instanceof DefaultPayload);
            boolean b2 = (payload instanceof DefaultPayload);
            if (b1 && b2) {

                DefaultPayload p1 = (DefaultPayload) lastPayload;
                DefaultPayload p2 = (DefaultPayload) payload;

                if (p1.equals(p2)) {
                    DefaultPayload newP = new DefaultPayload(p1, p2);
                    INode newNode = NodeFactory.create(newP);
                    addList.add(newNode);
                    removeList.add(lastNode);
                    removeList.add(n);
                    break;
                }
            }

            lastNode = n;
        }

        if (removeList.size() > 0) {
            AbstractNode parent = (AbstractNode) node;
            for (INode n : removeList) {
                parent.removeQuiet(n);
            }
            for (INode n : addList) {
                parent.addQuiet(n);
            }
        }

    }

}
